package com.towis.sample;

import java.util.Properties;

import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


/**
 * @Author : jakekim
 * @Date : 2014. 11. 20.
 * @Version : 0.1
 * @Description :
 */
public class GMailSender {

	public static void main(String[] args) {
		Properties p = new Properties();
		p.put("mail.smtp.user", "bresting@gmail.com"); // 구글계정
		p.put("mail.smtp.host", "smtp.gmail.com");
		p.put("mail.smtp.port", "465");
		p.put("mail.smtp.starttls.enable", "true");
		p.put("mail.smtp.auth", "true");

		p.put("mail.smtp.debug", "true");
		p.put("mail.smtp.socketFactory.port", "465");
		p.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		p.put("mail.smtp.socketFactory.fallback", "false");

		try {
			Authenticator auth = new SMTPAuthenticator();
			Session session = Session.getInstance(p, auth);
			session.setDebug(true); // 로그출력여부

			MimeMessage msg = new MimeMessage(session);
			String message = "Gmail SMTP 서버를 이용한 JavaMail 테스트";
			msg.setSubject("Gmail SMTP 서버를 이용한 JavaMail 테스트");
			
			Address fromAddr = new InternetAddress("bresting@gmail.com"); // 보내는사람
			msg.setFrom(fromAddr);
			Address toAddr = new InternetAddress("dojinkim@gridwiz.com"); // 받는 사람
			msg.addRecipient(Message.RecipientType.TO, toAddr);
			msg.setContent(message, "text/plain;charset=KSC5601");
			System.out.println("Message: " + msg.getContent());
			Transport.send(msg);
			System.out.println("Gmail SMTP서버를 이용한 메일보내기 성공");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	private static class SMTPAuthenticator extends javax.mail.Authenticator {
		public javax.mail.PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication("bresting", "dnflP@@12"); // Google id, pwd, 주의: @gmail.com은 제외
		}
	}
}